package com.windy.config;

import com.windy.app.constant.AuthConstant;
import com.windy.authorization.AuthorizationManager;
import com.windy.exception.MyServerAccessDeniedHandler;
import com.windy.exception.MyServerAuthenticationEntryPoint;
import com.windy.filter.IgnoreUrlsRemoveJwtFilter;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.SecurityWebFiltersOrder;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
import org.springframework.security.oauth2.server.resource.authentication.ReactiveJwtAuthenticationConverterAdapter;
import org.springframework.security.web.server.SecurityWebFilterChain;
import reactor.core.publisher.Mono;

/**
 * 资源服务器配置
 */
@AllArgsConstructor
@Configuration
@EnableWebFluxSecurity
public class ResourceServerConfig {

    private final AuthorizationManager authorizationManager;
    private final MyServerAccessDeniedHandler myServerAccessDeniedHandler;
    private final MyServerAuthenticationEntryPoint myServerAuthenticationEntryPoint;
    private final IgnoreUrlsRemoveJwtFilter ignoreUrlsRemoveJwtFilter;

    /**
     * Spring Secuity核心过滤器, 请求的认证入口SecurityWebFilterChain
     * @param serverHttpSecurity
     * @return
     */
    @Bean
    public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity serverHttpSecurity){
        serverHttpSecurity.oauth2ResourceServer().jwt()
            .jwtAuthenticationConverter(jwtAuthenticationConverter());
        //自定义处理JWT请求头过期或签名错误的结果
        serverHttpSecurity.oauth2ResourceServer().authenticationEntryPoint(myServerAuthenticationEntryPoint);
        //对白名单路径，直接移除JWT请求头
        serverHttpSecurity.addFilterBefore(ignoreUrlsRemoveJwtFilter, SecurityWebFiltersOrder.AUTHENTICATION);
        serverHttpSecurity.authorizeExchange()
            .pathMatchers("/actuator/**","/auth/oauth/token","/user/**").permitAll()
            .pathMatchers(HttpMethod.OPTIONS, "/**").permitAll()
            .anyExchange().access(authorizationManager)//鉴权管理器配置
            .and().exceptionHandling()
            .accessDeniedHandler(myServerAccessDeniedHandler)//自定义处理未认证异常
            .authenticationEntryPoint(myServerAuthenticationEntryPoint)//自定义处理JWT请求头过期或签名错误的结果
            .and().csrf().disable();
        return serverHttpSecurity.build();
    }

    /**
     * 配置jwt权限转换属性
     * @return
     */
    @Bean
    public Converter<Jwt, ? extends Mono<? extends AbstractAuthenticationToken>> jwtAuthenticationConverter(){
        JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
        jwtGrantedAuthoritiesConverter.setAuthorityPrefix(AuthConstant.AUTHORITY_PREFIX);
        //注意：这个AuthoritiesClaimName不能和JwtTokenEnhancer自定义的信息的key一致
        jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName(AuthConstant.AUTHORITY_CLAIM_NAME);
        JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
        jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwtGrantedAuthoritiesConverter);
        return new ReactiveJwtAuthenticationConverterAdapter(jwtAuthenticationConverter);
    }
}
